package net.lab1024.sa.admin.module.business.pdf.util;

import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * OCR配置检查工具类
 * 
 * @Author: SmartAdmin
 * @Date: 2024-01-01
 * @Copyright: 1024创新实验室
 */
@Component
public class OcrConfigChecker {

    /**
     * 检查OCR配置状态
     */
    public OcrConfigStatus checkOcrConfig(String tessDataPath) {
        OcrConfigStatus status = new OcrConfigStatus();
        
        try {
            // 检查tessdata目录是否存在
            File tessDataDir = new File(tessDataPath);
            if (!tessDataDir.exists()) {
                status.setAvailable(false);
                status.addError("Tesseract数据目录不存在: " + tessDataPath);
                return status;
            }
            
            if (!tessDataDir.isDirectory()) {
                status.setAvailable(false);
                status.addError("指定路径不是目录: " + tessDataPath);
                return status;
            }
            
            // 检查语言包文件
            List<String> availableLanguages = new ArrayList<>();
            File[] files = tessDataDir.listFiles((dir, name) -> name.endsWith(".traineddata"));
            
            if (files == null || files.length == 0) {
                status.setAvailable(false);
                status.addError("未找到任何语言包文件(.traineddata)");
                return status;
            }
            
            for (File file : files) {
                String language = file.getName().replace(".traineddata", "");
                availableLanguages.add(language);
            }
            
            status.setAvailableLanguages(availableLanguages);
            
            // 尝试初始化Tesseract
            Tesseract tesseract = new Tesseract();
            tesseract.setDatapath(tessDataPath);
            
            // 检查是否有中文语言包
            boolean hasChinese = availableLanguages.stream()
                    .anyMatch(lang -> lang.startsWith("chi_") || lang.equals("chi_sim") || lang.equals("chi_tra"));
            
            if (hasChinese) {
                // 优先使用中文简体
                if (availableLanguages.contains("chi_sim")) {
                    tesseract.setLanguage("chi_sim");
                    status.setDefaultLanguage("chi_sim");
                } else if (availableLanguages.contains("chi_tra")) {
                    tesseract.setLanguage("chi_tra");
                    status.setDefaultLanguage("chi_tra");
                }
            } else if (availableLanguages.contains("eng")) {
                tesseract.setLanguage("eng");
                status.setDefaultLanguage("eng");
            } else {
                // 使用第一个可用的语言
                tesseract.setLanguage(availableLanguages.get(0));
                status.setDefaultLanguage(availableLanguages.get(0));
            }
            
            // 测试OCR功能
            try {
                // 创建一个简单的测试图片（1x1像素的白色图片）
                java.awt.image.BufferedImage testImage = new java.awt.image.BufferedImage(1, 1, java.awt.image.BufferedImage.TYPE_INT_RGB);
                testImage.setRGB(0, 0, java.awt.Color.WHITE.getRGB());
                
                String result = tesseract.doOCR(testImage);
                status.setAvailable(true);
                status.addInfo("OCR功能测试成功");
                
            } catch (TesseractException e) {
                status.setAvailable(false);
                status.addError("OCR功能测试失败: " + e.getMessage());
            }
            
        } catch (Exception e) {
            status.setAvailable(false);
            status.addError("OCR配置检查异常: " + e.getMessage());
        }
        
        return status;
    }
    
    /**
     * OCR配置状态类
     */
    public static class OcrConfigStatus {
        private boolean available = false;
        private String defaultLanguage;
        private List<String> availableLanguages = new ArrayList<>();
        private List<String> errors = new ArrayList<>();
        private List<String> infos = new ArrayList<>();
        
        public void addError(String error) {
            errors.add(error);
        }
        
        public void addInfo(String info) {
            infos.add(info);
        }
        
        // Getters and Setters
        public boolean isAvailable() {
            return available;
        }
        
        public void setAvailable(boolean available) {
            this.available = available;
        }
        
        public String getDefaultLanguage() {
            return defaultLanguage;
        }
        
        public void setDefaultLanguage(String defaultLanguage) {
            this.defaultLanguage = defaultLanguage;
        }
        
        public List<String> getAvailableLanguages() {
            return availableLanguages;
        }
        
        public void setAvailableLanguages(List<String> availableLanguages) {
            this.availableLanguages = availableLanguages;
        }
        
        public List<String> getErrors() {
            return errors;
        }
        
        public void setErrors(List<String> errors) {
            this.errors = errors;
        }
        
        public List<String> getInfos() {
            return infos;
        }
        
        public void setInfos(List<String> infos) {
            this.infos = infos;
        }
        
        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append("OCR配置状态:\n");
            sb.append("可用性: ").append(available ? "是" : "否").append("\n");
            sb.append("默认语言: ").append(defaultLanguage != null ? defaultLanguage : "无").append("\n");
            sb.append("可用语言: ").append(availableLanguages).append("\n");
            
            if (!errors.isEmpty()) {
                sb.append("错误信息:\n");
                for (String error : errors) {
                    sb.append("  - ").append(error).append("\n");
                }
            }
            
            if (!infos.isEmpty()) {
                sb.append("信息:\n");
                for (String info : infos) {
                    sb.append("  - ").append(info).append("\n");
                }
            }
            
            return sb.toString();
        }
    }
} 